<template>
  <div class="teamTree-page">
    <Card :bordered="true" dis-hover class="ivu-mb">
      <div slot="title">
        <Dropdown>
          <Button type="primary" ghost @click.native="handleOpenCreateHeader">
            添加班组
          </Button>
        </Dropdown>
        <Button
          type="primary"
          ghost
          class="ivu-ml"
          v-show="!toggleExpand"
          @click="handleToggleExpandAll(true)"
        >
          <Icon type="md-list" />
          全部展开
        </Button>
        <Button
          type="primary"
          ghost
          class="ivu-ml"
          v-show="toggleExpand"
          @click="handleToggleExpandAll(false)"
        >
          <Icon type="md-list" />
          全部收起
        </Button>
        <Button
          type="error"
          ghost
          class="ivu-ml"
          v-show="selectedData.length"
          @click="handleDeleteMultiple"
        >
          <Icon type="md-trash" />
          批量删除
        </Button>
      </div>
      <div :style="menuListStyle">
        <div class="ivu-p-8">
          <Input
            v-if="menuList.length || query !== ''"
            v-model="query"
            search
            placeholder="输入班组名称搜索"
            @on-change="handleSearch"
          />
        </div>
        <Tree
          :data="menuList"
          show-checkbox
          check-strictly
          @on-select-change="handleSelectNode"
          @on-check-change="handleCheckNode"
          @on-contextmenu="handleContextMenu"
        >
          <template slot="contextMenu" v-if="showContextMenu">
            <DropdownItem @click.native="handleContextMenuEdit"
              >编辑</DropdownItem
            >
            <DropdownItem @click.native="handleContextMenuRead"
              >查看</DropdownItem
            >
            <DropdownItem
              divided
              @click.native="handleContextMenuDelete"
              style="color: #ed4014"
              >删除
            </DropdownItem>
          </template>
        </Tree>
      </div>
    </Card>
    <new-add-modal
      v-bind="addNewPanel"
      ref="addModal"
      :modelType="modelType"
      :columns="formColumns"
      :rules="rules"
      :zIndex="zIndex"
      @submit="handleNewAddSubmit"
    ></new-add-modal>
    <edit-modal
      v-bind="editPanel"
      :modelType="modelType"
      :columns="formColumns"
      :rules="rules"
      :zIndex="zIndex"
      @submit="handleEditSubmit"
    ></edit-modal>
    <read-modal
      v-bind="readPanel"
      :modelType="modelType"
      :columns="columns"
      :rules="rules"
      :zIndex="zIndex"
    ></read-modal>
    <bind-person
        :personPanel="selectPanel"
        :isSingleCheck="isSingleCheck"
        :selectionData="selectionData"
        @submit="submitSingleCheck">
    ></bind-person>
  </div>
</template>

<script>
    import { cloneDeep } from 'lodash';
    import newAddModal from '@/pages/components/newAddModal.vue';
    import editModal from '@/pages/components/editModal.vue';
    import readModal from '@/pages/components/readModal.vue';
    import bindPerson from '@/pages/components/bindPerson.vue';
    import { typeClassName } from '@/pages/config/classNameMap';
    import logicTreeMixin from '@/pages/components/mixins/logicTreeMixin'
    import columnsMixin from './config'
    export default {
        components: { newAddModal, editModal, readModal, bindPerson },
        mixins: [logicTreeMixin,columnsMixin],
        props: {
            classObject: {
                default: () => {
                    return null;
                }
            },
            className: {
                default: () => {
                    return '';
                }
            },
            type: {
                default: () => {
                    return '';
                }
            },
            modelType: {
                default: () => {
                    return '';
                }
            },
            data: {
                default: () => {
                    return [];
                }
            },
            addNewPanel: {
                default: () => {
                    return {
                        width: 1024,
                        zIndex: 100,
                        titleStyle: {},
                        drawer: {
                            show: false
                        },
                        cols: 2
                    }
                }
            },
            editPanel: {
                default: () => {
                    return {
                        width: 1024,
                        zIndex: 100,
                        titleStyle: {},
                        drawer: {
                            show: false
                        },
                        cols: 2,
                        data: {}
                    }
                }
            },
            readPanel: {
                width: 1024,
                zIndex: 100,
                titleStyle: {},
                drawer: {
                    show: false
                },
                cols: 2,
                data: {}
            }
        },
        data () {
            return {
                rules: {
                    sf_code: [
                        { required: true, message: '不能为空', trigger: 'blur' }
                    ],
                    sf_name: [
                        { required: true, message: '不能为空', trigger: 'blur' }
                    ]
                },
                currentNode: {
                    id: 'root',
                    title: 'root'
                },
                menuList: [],
                sourceMenuList: [],
                zIndex: 1000,
                selectedData: [],
                toggleExpand: true,
                query: '',
                loading: false,
                showContextMenu: true,
                teamClassOptions: [{ label: '早', value: '早' }, { label: '中', value: '中' }, { label: '晚', value: '晚' }], // 班次信息，下拉框使用
                deptObject: null, // 关联所有部门实例
                deptOptions: [], // 部门信息，下拉框使用
                selectPanel: {
                    width: 1024,
                    zIndex: 1001,
                    titleStyle: {},
                    drawer: {
                        show: false
                    },
                    cols: 2,
                    data: {}
                },
                isSingleCheck: true,
                selectionData: [],
            };
        },
        computed: {
            menuListStyle () {
                return {
                    height: document.body.clientHeight - 330 + 'px',
                    overflow: 'auto'
                }
            },
        },
        watch: {
            data: {
                handler () {
                    this.menuList = this.getChildren('root')
                    this.sourceMenuList = this.menuList
                },
                deep: true
            }
        },
        mounted () {
            this.menuList = this.getChildren('root')
            this.sourceMenuList = this.menuList
            this.deptObject = this.$modelObject.create(`${typeClassName['dept'].modelType}`);
            this.getDept();
        },
        methods: {
            // 获取所有部门信息
            getDept () {
                let filter = {
                    className: typeClassName['dept'].className,
                    type: typeClassName['dept'].type
                }
                let newFilter = '';
                if (this.tools.isReal(filter)) {
                    newFilter = this.deptObject.util.getFilter(filter);
                }
                this.deptObject
                    .query(newFilter)
                    .then((flag) => {
                        if (flag) {
                            let deptOptions = [];
                            if (this.deptObject.isValidHier()) {
                                deptOptions = this.getChildren('root', this.deptObject.record.hier[0].basic)
                            }
                            this.deptOptions = deptOptions;
                        } else {
                            this.deptOptions = [];
                        }
                });
            },
            getChildren (parentId, data = this.data) {
                let children = [];
                let list = data.filter(item => item.parentId === parentId);
                list.map(item => {
                    if (!!item.pointer && item.pointer.className === typeClassName['person'].className) {
                        return;
                    }
                    children.push({
                        title: item.values.sf_name ? `${item.values.sf_name}` : item.name,
                        label: item.values.sf_name ? `${item.values.sf_name}` : item.name,
                        id: item.id,
                        value: item.id,
                        parentId: item.parentId,
                        contextmenu: true,
                        data: item,
                        pointer: item.pointer,
                        children: this.getChildren(item.id, data),
                        disabled: !!item.pointer && item.pointer.className === typeClassName['person'].className
                    })
                });
                return children;
            },
            // 新增班组保存
            handleNewAddSubmit (data) {
                let newData = {
                    id: this.tools.uuid(8),
                    name: data.values['sf_name'],
                    title: data.values['sf_name'],
                    values: {
                        ...data.values
                    },
                    pointer: {},
                    parentId: this.currentNode.id
                };
                this.$emit('handleNewAddSubmit', newData)
            },
            // 打开编辑班组弹窗
            handleContextMenuEdit () {
                this.loading = true;
                if (this.classObject.isValidHier()) {
                    let index = this.classObject.hier[0].basic.findIndex(d => d.id === this.currentNode.id)
                    if (index !== -1) {
                        let currentObj = cloneDeep(this.classObject.hier[0].basic[index]);
                        this.$set(this.editPanel, 'data', currentObj);
                        this.$set(this.editPanel.drawer, 'show', true);
                        // 已选组长,单选
                        this.selectionData = [{id:currentObj.values.leaderId,label:currentObj.values.leader,code:currentObj.values.leaderCode}]
                    }
                    this.loading = false;
                } else {
                    this.loading = false;
                }
            },
            // 编辑班组保存
            handleEditSubmit (data) {
                let newData = {
                    id: data.id,
                    name: data.name,
                    title: data.name,
                    values: {
                        ...data.values
                    },
                    pointer: {},
                    parentId: !!data.parentId ? data.parentId : 'root'
                };
                this.$emit('handleEditSubmit', newData)
            },
            // 打开查看班组弹窗
            handleContextMenuRead () {
                this.loading = true;
                if (this.classObject.isValidHier()) {
                    let index = this.classObject.hier[0].basic.findIndex(d => d.id === this.currentNode.id)
                    if (index !== -1) {
                        this.$set(this.readPanel, 'data', this.classObject.hier[0].basic[index].values);
                        this.$set(this.readPanel.drawer, 'show', true);
                    }
                    this.loading = false;
                } else {
                    this.loading = false;
                }
            },
            // 左击选中
            handleSelectNode (currentArr, item) {
                this.currentNode = { ...item }
                if (!!item.pointer && item.pointer.className === typeClassName['person'].className) {
                    this.showContextMenu = false;
                } else {
                    this.showContextMenu = true;
                }
                this.$emit('handleSelectNode', this.currentNode)
            },
            // 右击
            handleContextMenu (item) {
                this.currentNode = { ...item }
                if (!!item.pointer && item.pointer.className === typeClassName['person'].className) {
                    this.showContextMenu = false;
                } else {
                    this.showContextMenu = true;
                }
                this.$emit('handleSelectNode', this.currentNode)
            },
            // 删除班组
            handleContextMenuDelete () {
                if (this.submitting) return;
                this.$Modal.confirm({
                    title: this.lang['confirmDelete'],
                    cancelText: this.lang['cancel'],
                    content: `您确认要删除班组<strong>${this.currentNode.title}</strong>吗？`,
                    loading: this.loading,
                    onOk: () => {
                        this.deleteMenu();
                    }
                });
            },
            // 确认删除班组
            deleteMenu () {
                let menu = this.data.find(item => item.parentId === this.currentNode.id);
                if (!!menu) {
                    this.$Modal.remove();
                    this.$Message.warning('请先删除子班组并解绑人员');
                    return;
                }
                let names = [];
                if (!!this.currentNode.data && !!this.currentNode.data.name) {
                    names = [this.currentNode.data.name]
                }
                let pointer = { className: this.className, type: this.type }
                // 解绑hier中某项的接口
                this.loading = true;
                this.classObject
                    .runRemoveRegister(pointer, names)
                    .then((flag) => {
                        if (flag) {
                            this.loading = false;
                            names.forEach((name) => {
                                let index = this.data.findIndex(
                                    (d) => d.name === name
                                );
                                if (index !== -1) {
                                    this.classObject.record.hier[0].basic.splice(index, 1);
                                }
                            });
                            this.currentNode = {
                                id: 'root',
                                title: '未选中'
                            }
                            this.$emit('handleSelectNode', this.currentNode)
                        } else {
                            this.loading = false;
                        }
                });
            },
            // 批量删除班组
            handleDeleteMultiple () {
                if (this.submitting) return;
                const ids = this.selectedData.map(item => item.data.name);
                const titles = this.selectedData.map(item => item.title);
                this.$Modal.confirm({
                    title: this.lang['confirmDelete'],
                    cancelText: this.lang['cancel'],
                    content: `您确认要删除班组<strong>${titles}</strong>吗？`,
                    loading: this.loading,
                    onOk: () => {
                        this.deleteMenuMultiple(ids);
                    }
                });
            },
            // 确认批量删除班组
            deleteMenuMultiple (names) {
                for (let i = 0; i < names.length; i++) {
                    let menu = this.data.find(item => item.parentId === names[i]);
                    if (!!menu) {
                        this.$Modal.remove();
                        this.$Message.warning('请先删除' + menu.title + '子班组并解绑人员');
                        return;
                    }
                }
                let pointer = { className: this.className, type: this.type }
                // 解绑hier中某项的接口
                this.loading = true;
                this.classObject
                    .runRemoveRegister(pointer, names)
                    .then((flag) => {
                        if (flag) {
                            this.loading = false;
                            names.forEach((name) => {
                                let index = this.data.findIndex(
                                    (d) => d.name === name
                                );
                                if (index !== -1) {
                                    this.classObject.record.hier[0].basic.splice(index, 1);
                                }
                            });
                            this.currentNode = {
                                id: 'root',
                                title: '未选中'
                            }
                            this.$emit('handleSelectNode', this.currentNode)
                        } else {
                            this.loading = false;
                        }
                });
            },
            // 打开绑定班长弹框
            selectLeader () {
                this.$set(this.selectPanel.drawer, 'show', true)
            },
            //  绑定组长确认
            submitSingleCheck (selection) {
                let row = selection[0]||{}
                let {leader,leaderId,leaderCode} ={leader:row.label,leaderId:row.id,leaderCode:row.code}
                if (this.addNewPanel.drawer.show) {
                    let newValues = {...this.$refs.addModal.data.values,leader,leaderId,leaderCode}
                    this.$set(this.$refs.addModal.data, 'values',newValues);
                    this.$set(this.selectPanel.drawer, 'show', false)
                } else if (this.editPanel.drawer.show) {
                    let data = { ...this.editPanel.data }
                    data.values = {...data.values,leader,leaderId,leaderCode}
                    this.$set(this.editPanel, 'data', data);
                    this.$set(this.editPanel.drawer, 'show', false)
                    this.$set(this.selectPanel.drawer, 'show', false)
                    this.$nextTick(() => {
                        this.$set(this.editPanel.drawer, 'show', true)
                    })
                }
            }
        }
    };
</script>
<style scoped lang="scss">
.teamTree-page{
    width: 600px;
    margin-top: 10px;
}
</style>
